package com.open.capacity.reimburse.service.impl;

import com.open.capacity.model.system.SysUser;
import com.open.capacity.reimburse.util.uuid.UUIDUtils;
import com.open.capacity.user.model.SysArea;
import com.open.capacity.user.service.SysAreaService;
import com.open.capacity.user.service.SysUserService;
import com.open.capacity.utils.DateUtil;
import com.open.capacity.utils.StringUtil;
import com.open.capacity.utils.SysUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.open.capacity.commons.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

import org.apache.commons.collections4.MapUtils;

import com.open.capacity.reimburse.entity.StdHotel;
import com.open.capacity.reimburse.dao.StdHotelDao;
import com.open.capacity.reimburse.service.StdHotelService;

@Slf4j
@Service
public class StdHotelServiceImpl implements StdHotelService {

    @Autowired
    private StdHotelDao stdHotelDao;

    @Autowired
    private SysAreaService areaService;

    @Autowired
    private SysUserService userService;

    /**
     * 添加
     *
     * @param stdHotel
     */
    public int save(StdHotel stdHotel) throws Exception {
        SysUser loginUser = SysUserUtil.getLoginAppUser();

        validition(stdHotel);
        SysArea province = areaService.findById(stdHotel.getProvinceId());
        stdHotel.setProvinceName(province.getAreaName());

        String[] cityIds = stdHotel.getCityId().split(",");
        String cityName = "";
        for (String c : cityIds) {
            SysArea city = areaService.findById(c);
            if (StringUtil.isEmpty(cityName)) {
                cityName += city.getAreaName();
            } else {
                cityName += "," + city.getAreaName();
            }
        }
        stdHotel.setCityName(cityName);

        if (StringUtil.isNotEmpty(stdHotel.getCountyId())) {
            String[] countyIds = stdHotel.getCountyId().split(",");
            String countyName = "";
            for (String c : countyIds) {
                SysArea county = areaService.findById(c);
                if (StringUtil.isEmpty(countyName)) {
                    countyName += county.getAreaName();
                } else {
                    countyName += "," + county.getAreaName();
                }
            }
            stdHotel.setCountyName(countyName);
        }

        stdHotel.setId(UUIDUtils.getOriginalUUIDWithoutBar());
        stdHotel.setUpdateUserid(loginUser.getId());
        stdHotel.setUpdateUsername(loginUser.getRealName());
        stdHotel.setUpdateTime(new Date());
        return stdHotelDao.save(stdHotel);
    }

    private void validition(StdHotel stdHotel) throws Exception {
        if (StringUtil.isNotEmpty(stdHotel.getHighSeason())) {
            if (stdHotel.getLevel1Highstandard() == null || stdHotel.getLevel1Highstandard().compareTo(BigDecimal.ZERO) < 0
                    || stdHotel.getLevel2Highstandard() == null || stdHotel.getLevel2Highstandard().compareTo(BigDecimal.ZERO) < 0
                    || stdHotel.getLevel3Highstandard() == null || stdHotel.getLevel3Highstandard().compareTo(BigDecimal.ZERO) < 0) {
                throw new Exception("旺季浮动标准配置错误");
            }
        }
    }

    /**
     * 修改
     *
     * @param stdHotel
     */
    public int update(StdHotel stdHotel) {
        SysArea province = areaService.findById(stdHotel.getProvinceId());
        stdHotel.setProvinceName(province.getAreaName());

        String[] cityIds = stdHotel.getCityId().split(",");
        String cityName = "";
        for (String c : cityIds) {
            SysArea city = areaService.findById(c);
            if (StringUtil.isEmpty(cityName)) {
                cityName += city.getAreaName();
            } else {
                cityName += "," + city.getAreaName();
            }
        }
        stdHotel.setCityName(cityName);

        if (StringUtil.isNotEmpty(stdHotel.getCountyId())) {
            String[] countyIds = stdHotel.getCountyId().split(",");
            String countyName = "";
            for (String c : countyIds) {
                SysArea county = areaService.findById(c);
                if (StringUtil.isEmpty(countyName)) {
                    countyName += county.getAreaName();
                } else {
                    countyName += "," + county.getAreaName();
                }
            }
            stdHotel.setCountyName(countyName);
        }
        stdHotel.setUpdateTime(new Date());
        return stdHotelDao.update(stdHotel);
    }


    /**
     * 删除
     *
     * @param id
     */
    public int delete(String id) {
        return stdHotelDao.delete(id);
    }

    /**
     * 查询记录
     *
     * @param id
     * @return
     */
    public StdHotel findById(String id) {
        return stdHotelDao.findById(id);
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    public PageResult<StdHotel> pageAll(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<StdHotel> list = stdHotelDao.findAll(params);
        list.forEach(item -> {
            if (StringUtil.isNotEmpty(item.getHighSeason())) {
                item.setHighSeasonStr(item.getHighSeason());
            }
        });

        PageInfo<StdHotel> pageInfo = new PageInfo(list);

        return PageResult.<StdHotel>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }


    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<StdHotel> findAll(Map<String, Object> params) {
        return stdHotelDao.findAll(params);
    }


    /**
     * 校验住宿费是否超标
     *
     * @param userId        当事人
     * @param followUserids 随行人员
     * @param destination   目的地
     * @param startDate     开始日期
     * @param endDate       结束日期
     * @param money         金额
     * @return
     */
    @Override
    public String verify(String userId, String followUserids, Integer persons, String destination, Date startDate, Date endDate, BigDecimal money) {
        String error_msg = "";
        String[] destinationArr = destination.split("/");
        String provinceId = destinationArr.length > 0 ? destinationArr[0] : "";
        String cityId = destinationArr.length > 1 ? destinationArr[1] : "";
        String countyId = destinationArr.length > 2 ? destinationArr[2] : "";
        int personCounts = (StringUtil.isEmpty(followUserids) ? 0 : followUserids.split(",").length) + 1;
        //判断手工填写的人数是否比随行人员少，以少的为准
        if (persons < personCounts) {
            personCounts = persons;
        }
        int days = DateUtil.getBetweenDay(startDate, endDate);
        if (days <= 0) {
            days = 1;
        }
        SysUser user = userService.findById(userId);

        Map<String, Object> params = new HashMap<>();
        params.put("provinceId", provinceId);
        params.put("cityId", cityId);
        params.put("countyId", countyId);
        int month = startDate.getMonth() + 1;
        params.put("month", month);
        List<StdHotel> list = stdHotelDao.findAll(params);

        boolean flag;
        if (CollectionUtils.isNotEmpty(list)) {
            StdHotel item = list.get(0);
            BigDecimal standard = BigDecimal.ZERO;
            BigDecimal price = BigDecimal.ZERO;
            String levelStr = "";
            boolean isHighSeason = item.getHighSeason() == null ? false : Arrays.stream(item.getHighSeason().split(",")).filter(a -> a.equals(String.valueOf(month))).count() > 0;
            switch (user.getLevels()==null?"3":user.getLevels()) {
                case "1"://部级
                    levelStr = "部级";
                    price = isHighSeason ? item.getLevel1Highstandard() : item.getLevel1Standard();
                    break;
                case "2"://司局级
                    levelStr = "司局级";
                    price = isHighSeason ? item.getLevel2Highstandard() : item.getLevel2Standard();
                    break;
                case "3"://普通
                    levelStr = "普通";
                    price = isHighSeason ? item.getLevel3Highstandard() : item.getLevel3Standard();
                    break;

                default:
                    levelStr = "普通";
                    price = isHighSeason ? item.getLevel3Highstandard() : item.getLevel3Standard();
                    break;
            }

            standard = price.multiply(BigDecimal.valueOf(days)).multiply(BigDecimal.valueOf(personCounts));
            flag = money.compareTo(standard) <= 0;
            if (!flag) {
                String area = "";
                SysArea province = areaService.findById(provinceId);
                area += province.getAreaName();
                if (StringUtil.isNotEmpty(cityId)) {
                    SysArea city = areaService.findById(cityId);
                    area += city.getAreaName();
                }
                if (StringUtil.isNotEmpty(countyId)) {
                    SysArea county = areaService.findById(countyId);
                    area += county.getAreaName();
                }
                DecimalFormat decimalFormat = new DecimalFormat("###,###.00");
                error_msg = "<p>⊙ 住宿费用超标， " + levelStr + "干部在" + area + "的住宿标准是" + decimalFormat.format(standard) + "元</p>";
            }
        }
        return error_msg;
    }
}
